/*
 * 研发者：夏冬琦
 * 日期：2019-12-30
 */

class MyUtils {
	copyProps(oldObj) {
		let newObj = {};
		for (let prop in oldObj) {//遍历对象的属性名称（键）
			newObj[prop] = oldObj[prop];
		}
		return newObj;
	}
}

const myutils = new MyUtils();

//自定义axios实例
const $axios = axios.create({
	baseURL: 'http://localhost:8080',
	withCredentials: true //表示跨域请求时是否需要使用凭证
});

//将$axios定义为Vue的原型属性
Vue.prototype.$axios = $axios;


if (Vue) {

	Vue.prototype.$axios = $axios;//为vue设置原型属性$axios

	Vue.prototype.$ajax = function (getAxiosPromise) {



		let promise = new Promise((resolve, reject) => {

			try {

				var loadIndex = layer.load();//显示加载提示

				getAxiosPromise()
					.then(res => {//处理成功响应

						layer.close(loadIndex);//关闭加载提示

						let result = res.data;//获取服务器的响应结果


						if (!result.hasOwnProperty('logined')) {
							//服务器响应数据无已登录标志属性logined

							resolve(result);//由then方法的参数（一个函数）继续处理响应结果
							return;
						}

						if (!result.logined) {
							//服务器响应结果的已登录标志属性logined的值为false

							layer.msg(
								'您已下线，请登录！',
								{ icon: 4, time: 1500 },
								function () {
									window.top.location.href = '../../safty/login/index.html';
								}
							);

							return;
						}

						//由then方法的参数（一个函数）继续处理响应结果
						resolve(result);

					})
					.catch(err => {//处理错误响应

						layer.close(loadIndex);//关闭加载提示

						console.log(err);//控制台打印错误信息



						if (!err.response) {//若错误对象不存在response属性或者该属性值可转换为false

							layer.msg(
								'错误: ' + err.message,
								{ icon: 2, time: 1500 }
							);

							return;

						}

						//若服务器没有响应
						if (err.request.status == 0) {

							layer.msg(
								`地址 ${err.config.url} 没有响应，请检查服务器地址是否正确。`,
								{ icon: 2, time: 1500 }
							);
							return;
						}

						layer.msg(
							`响应错误：${err.response.status}`,
							{ icon: 2, time: 1500 }
						);


					});

			} catch (error) {//发生异常

				console.log(error);

				layer.msg(
					'JavaScript代码错误:' + error.message,
					{ icon: 2, time: 1500 }
				);

				throw e;
			}

		});

		return promise;

	};

	Vue.prototype.$myoprate = function (getAxiosPromise, confirmInfo) {

		const _this = this;

		let promise = new Promise((resolve, reject) => {

			if (confirmInfo && confirmInfo.message && confirmInfo.title) {

				layer.confirm(confirmInfo.message, { icon: 3, title: confirmInfo.title }, function (index) {

					_this.$ajax(getAxiosPromise)
						.then((result) => {

							if (result.success) {
								layer.msg(
									result.message,
									{ icon: 1, time: 1500 }
								);

								resolve(result);
							} else {

								layer.alert(result.message, { icon: 2 });

							}

						});

					layer.close(index);

				});

			} else {
				_this.$ajax(getAxiosPromise)
					.then((result) => {

						if (result.success) {
							layer.msg(
								result.message,
								{ icon: 1, time: 1500 }
							);

							resolve(result);
						} else {

							layer.alert(result.message, { icon: 2 });

						}

					});

			}

		});

		return promise;

	}

	Vue.prototype.$myGet = function (url, config) {

		let promise = new Promise((resolve, reject) => {

			this.$ajax(() => $axios.get(url, config))
				.then((result) => {
					resolve(result);
				});

		});

		return promise;
	};


	Vue.prototype.$myPost = function (url, data, config) {

		return this.$myoprate(() => { return $axios.post(url, data, config); }, config);

	};

	Vue.prototype.$myPut = function (url, data, config) {

		return this.$myoprate(() => { return $axios.put(url, data, config); }, config);

	};

	Vue.prototype.$myDelete = function (url, config) {

		return this.$myoprate(() => { return $axios.delete(url, config); }, config);

	};


	Vue.prototype.$myLogined = function () {

		return this.$myGet('/pub/currUser');

	};

	/*
	给Vue添加原型方法，以application/x-www-form-urlencoded编码格式，向服务器发出post请求，返回promise，
	then方法的参数是一个函数，该函数的参数为服务器发送的未经包装响应数据
	*/
	Vue.prototype.$post = function (url, data, config) {
		if (!config) {
			config = {};
		}

		if (!config.headers) {
			config.headers = { "Content-Type": 'application/x-www-form-urlencoded' };
		} else {
			config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
		}

		config.transformRequest = [function (data, headers) {

			if (!data || typeof (data) === 'string') {
				return data;
			}

			if (!(typeof (data) === 'object')) {
				return data;
			}


			let params = [];
			for (let prop in data) {
				if (data[prop] instanceof Array) {
					let arr = data[prop];
					for (let i = 0; i < arr.length; i++) {
						params.push(prop + "=" + arr[i]);
					}
				} else {
					params.push(prop + "=" + data[prop]);
				}

			}
			return params.join("&");

		}];

		return this.$myoprate(() => { return $axios.post(url, data, config); }, config);

	};

	/*
		给Vue添加原型方法 向服务器发出get请求，返回promise，
		then方法的参数是一个函数，该函数的参数为服务器发送的未经包装响应数据
	*/
	Vue.prototype.$get = Vue.prototype.$myGet;


}